package com.li.client;

import com.li.annotation.Component;

import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ComponentScan {



    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        // 目前只知道一个包的名字，扫描这个包下所有的类，当这个类上有@Component注解的时候，实例化该对象，然后放到map集合中
        String packageName = "com.li.bean";
        //包名变目录
        String path = packageName.replaceAll("\\.", "/");
        System.out.println(path);
        //获取系统类加载器，自动从类的根路径下开始加载资源
        URL url = ClassLoader.getSystemClassLoader().getResource(path);
        File file = new File(url.getPath());
        File[] files = file.listFiles();
        Arrays.stream(files).forEach(f -> {
            System.out.println(f.getName());
            String className = packageName + "." + f.getName().split("\\.")[0];
            try {
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(Component.class)) {
                    Component annotation = clazz.getAnnotation(Component.class);
                    Constructor<?> constructor = clazz.getConstructor();
                    Object bean = constructor.newInstance();
                    map.put(annotation.value(), bean);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        System.out.println(map);
    }
}
